odoo.define('my_qrcode_scanner.scanner', function (require) {
"use strict";

var ajax = require('web.ajax');
ajax.loadJS('https://cdn.jsdelivr.net/npm/jsqr@1.3.1/dist/jsQR.min.js');
var core = require('web.core');
var ListController = require('web.ListController'); // 这个是要用的插件默认写法
var session = require('web.session');
var ListRenderer = require('web.ListRenderer');
var _t = core._t;
var QWeb = core.qweb;
var BasicView = require('web.BasicView');
var deviceId = null;
console.log("ListController.include")


ListController.include({

    init: function () {
        this._super.apply(this, arguments);
        this.Scanner = Scanner()
        this.camera_list =  this.Scanner.getCameraDevices();
        this.camera_index = this.camera_list.length? this.camera_list.length - 1 : 0;
        this.stream = null
        this.width=0
        this.height=0
    },

    events: Object.assign({}, ListController.prototype.events, {
        'click .o_click_camera_open': '_click_camera_open',
        'click .o_click_camera_change': '_click_camera_change',
        'click .o_click_camera_close': '_o_click_camera_close',
    }),

    renderButtons: function ($node) {
        var $buttons = this._super.apply(this, arguments);
        if (this.modelName === "factory.visitor") {
            var button_start = $(_t("<button id='start_camera' type='button' class='btn btn-success btn_margin o_click_camera_open' style='margin-right: 20px'><span class='d-none d-sm-inline'></span>打开摄像头</button>"))
            var button_toggle = $(_t("<button id='toggle_camera' type='button' class='btn btn-primary btn_margin o_click_camera_change'><span class='d-none d-sm-inline'></span>切换摄像头</button>"))
            var button_close = $(_t("<button id='close_camera' type='button' class='btn btn-warning btn_margin o_click_camera_close'><span class='d-none d-sm-inline'></span>关闭摄像头</button>"))
            var $button_vedio = $(_t("<video id=\"video\" autoplay playsinline></video>"))
            $button_vedio.css({
                'width': this.width + 'px', // 添加 'px' 来指定单位是像素
                'height': this.height + 'px' // 同样添加 'px'
            });

            // 下一句 是将 button_01添加到tree按钮的最后面一个位置
             this.$buttons.append($button_vedio);
            this.$buttons.append(button_start);
            // this.$buttons.append(button_toggle);
            this.$buttons.append(button_close);

        }
        return $buttons;
    },
    //

    _click_camera_open: function (event) {
        console.log('点击了摄像头按钮')
        // 获取摄像机列表
        var $video = document.getElementById('video');
        $video.style.width = '1000px'; // 设置宽度为1000像素
        $video.style.height = '500px'; // 设置高度为500像素
        this.Scanner.start(this, this.camera_index, false);
    },
    _click_camera_change: function (event) {
        console.log('切换摄像头按钮')
        // 获取摄像机列表
        this.Scanner.toggleCamera(this);
    },

    _o_click_camera_close: function (event) {
        console.log('关闭摄像头按钮')
        var $video = document.getElementById('video');
        $video.style.width = '0px'; // 设置宽度为640像素
        $video.style.height = '0px'; // 设置高度为360像素
        // 获取摄像机列表
        this.Scanner.stop(this);
    },

});



var Scanner = function () {
    async function startCamera(ListController, camera_index, toggle) {
        stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true }
);
        var camera_list = await this.getCameraDevices()
        if (camera_list.length) {
        camera_index = !toggle ? camera_list.length - 1 : camera_index
        ListController.camera_index = camera_index;
        // var camera_index = await ListController.camera_index;
        // alert('设备列表为:' + camera_list + '设备个数' + camera_list.length + '当前设备索引是' + camera_index)
        deviceId = camera_list[camera_index];
        // deviceId = camera_list.length > 1? camera_list[1]: camera_list[0];
        var stream;
        var scanning = false;
        const constraints = {
            video: {
                deviceId: {exact: deviceId}
            }
        };
        try {
            // alert('当前设备为:' + deviceId)
            var video = document.getElementById('video');
            // const mediaStreamConstraints = { video: { facingMode: facingMode } };
            // stream = await navigator.mediaDevices.getUserMedia({ video: true });
            stream = await navigator.mediaDevices.getUserMedia(constraints);
            video.srcObject = stream;
            ListController.stream = stream;
            // 你可以在这里添加其他启动时的操作
            // console.log('Camera started with facingMode:', facingMode);
            // startButton.disabled = true;
            // stopButton.disabled = false;
            // scanButton.disabled = false;
            // scanning = true;
            // scanQRCode();
            //    alert('当前摄像头模式为：' + facingMode)

            // 监听视频元数据加载完成事件
            // addEventListener('loadedmetadata', () => {
            scanning = true;
            // alert('扫码开始')
            scanQRCode();
            // });
        } catch (error) {
            console.error('无法访问摄像头:', error);
            if (error.name === 'OverconstrainedError') {
            alert('无法访问指定的摄像头，可能是设备 ID 错误或权限问题。');
        } else if (error.name === 'NotAllowedError') {
            alert('用户拒绝了摄像头访问权限。');
        } else {
            console.error('无法访问摄像头:', error);
            alert('无法访问摄像头，请检查错误信息。');
        }

        }
        }

    }

    async function toggleCamera(ListController) {
        var camera_list = await ListController.camera_list;
        var camera_index = await ListController.camera_index;
        var video = document.getElementById('video');
        if (video.srcObject) {
            // alert('切换开始')
            // 切换摄像头
            if (camera_list.length > 1) {
                // alert('切换设备正式开始')
                var next_index = camera_index + 1;
                if (next_index >= camera_list.length) {
                    next_index = 0;
                }
                ListController.camera_index = next_index;
                // alert('切换设备索引为' + next_index)
                const tracks = video.srcObject.getTracks();
                tracks.forEach(track => track.stop()); // 停止当前视频流
                startCamera(ListController, next_index, true);
            }

            // // 更新video标签的facing-mode属性（可选，用于记录或后续使用）
            // video.setAttribute('facing-mode', newFacingMode);
        }
    }

    async function getCameraDevices() {
        var camera_list = [];
        await navigator.mediaDevices.enumerateDevices()
            .then(devices => {
                devices.forEach(device => {
                    if (device.kind === 'videoinput') {
                        // 根据label或deviceId选择你想要的摄像头
                        camera_list.push(device.deviceId)
                    }
                });
            })
            .catch(error => {
                console.error('无法枚举设备:', error);
            });
        return camera_list;
    }

    async function stopCamera(ListController) {
        // ... (与原始代码中的stopButton事件监听器相同)
        // var stream;
        // var scanning;
        // if (stream) {
        var video = await document.getElementById('video');
        // const tracks = video.srcObject.getTracks();
        // tracks.forEach(track => track.stop()); // 停止当前视频流
        const stream = await ListController.stream
        console.log(stream)
        if (stream){
            const tracks = stream.getTracks();
            tracks.forEach(track => track.stop());
        }
        // 假设canvas的父元素是document.body
        //  var canvas = document.getElementById('canvas');
        //  document.body.removeChild(canvas);
        //  alert('移除画布')

// 此时，canvas元素已经从DOM中移除，如果没有其他引用指向它，它将被垃圾回收

            video.srcObject = null;
            // startButton.disabled = false;
            // stopButton.disabled = true;
            // scanButton.disabled = true;
            // scanning = false;
        // }
    }

    function toggleScan() {
        var scanning;
        // ... (与原始代码中的scanButton事件监听器相同)
        if (scanning) {
            scanning = false;
            // scanButton.textContent = '开始扫描';
        } else {
            scanning = true;
            // scanButton.textContent = '停止扫描';
            scanQRCode();
        }
    }

    function scanQRCode() {
        // ... (与原始代码中的scanQRCode函数相同)
        //     if (!scanning) return;
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');
        // canvas.width = video.videoWidth;
        canvas.width = 1000;
        canvas.height = 1000;
        var video = document.getElementById('video');
        if (!video || video.readyState < 2) {
        // 视频未找到或未准备好
        requestAnimationFrame(scanQRCode);
        return;
        }
       try {

            // canvas.width = video.videoWidth;
            // canvas.height = video.videoHeight;
            context.drawImage(video, 0, 0, canvas.width, canvas.height);
            // context.drawImage(video, 0, 0, canvas.width, canvas.height);
            // context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
        const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
        const code = jsQR(imageData.data, imageData.width, imageData.height);
        if (code && parseInt(code.data)){
            var url = "https://visitor.zuru.cloud:5014/web#id="+ code.data + "&&model=factory.visitor&view_type=form"
            window.location.href = url;
            // window.location.href = "https://baidu.com";
        } else {
            requestAnimationFrame(scanQRCode);
        }
    } catch (error) {
            alert('扫描出错')
        console.error('Error getting image data:', error);
        requestAnimationFrame(scanQRCode);
    }
}

        return {
            start: startCamera,
            stop: stopCamera,
            toggleScan: toggleScan,
            toggleCamera: toggleCamera,
            getCameraDevices: getCameraDevices,
        };
    };


});